﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Apps;
using VAdvantage.Utility;
using VAdvantage.Logging;
using System.Data;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.Classes;
using VAdvantage.Controls;
using System.Windows.Forms;
using System.IO;
namespace VAdvantage.Install
{
    public partial class TranslationDialog : UserControl, FormPanel
    {
        private ToolTip _tooltip = new ToolTip();
        private int _WindowNo = 0;
        private FormFrame _frame;
        private static VLogger log = VLogger.GetVLogger(typeof(TranslationDialog).FullName);
        public TranslationDialog()
        {

        }

        public void Init(int windowNo, FormFrame frame)
        {
            InitializeComponent();
            //toolStripStatus.Text = Msg.GetMsg(Envs.GetCtx(), "Required Data");
            //this.Dock = DockStyle.Fill;
            log.Info("");
            _WindowNo = windowNo;
            _frame = frame;

            Envs.GetCtx().SetIsSOTrx(_WindowNo, true);
            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            //this.Height    =330;
            //this.Width= 449;
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            try
            {
                //tmr = new System.Windows.Forms.Timer();
                // tmr.Interval = 500;
                // tmr.Tick += new EventHandler(tmr_Tick); //  new System.Timers.ElapsedEventHandler(tmr_Elapsed);

                JbInit();
                DynInit();
                //frame.GetContentPane().Controls.Add((Control)this);
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, "", ex);
            }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }
        private void JbInit()
        {
            lClient.Content = Msg.Translate(Envs.GetCtx(), "AD_Client_ID");
            lLanguage.Content = Msg.Translate(Envs.GetCtx(), "AD_Language");

            // _tooltip.SetToolTip(lLanguage, Msg.Translate(Envs.GetCtx(), "IsSystemLanguage"));
            lTable.Content = Msg.Translate(Envs.GetCtx(), "AD_Table_ID");
            //
            btnExport.Content = Msg.GetMsg(Envs.GetCtx(), "Export");
            ///bExport.addActionListener(this);
            btnExport.Click += new RoutedEventHandler(btnExport_Click);
            btnImport.Content = Msg.GetMsg(Envs.GetCtx(), "Import");
            //bImport.addActionListener(this);
            btnImport.Click += new RoutedEventHandler(btnExport_Click);
        }



        void btnExport_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            ValueNamePair AD_Language = (ValueNamePair)cbLanguage.SelectedItem;// getSelectedItem();
            if (AD_Language == null)
            {
                //statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "LanguageSetupError"), true);
                // toolStripStatus.Text = Msg.GetMsg(Env.GetCtx(), "LanguageSetupError").Replace("\n", "").Replace("\r", "");
                lblStatus.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "LanguageSetupError"));
                return;
            }
            ValueNamePair AD_Table = (ValueNamePair)cbTable.SelectedItem;// getSelectedItem();
            if (AD_Table == null || AD_Table.GetName() == "")
                return;
            bool imp = true;//
            if (btn.Name == "btnExport")
            {
                imp = false;
            }
            KeyNamePair AD_Client = (KeyNamePair)cbClient.SelectedItem;
            int AD_Client_ID = -1;
            if (AD_Client != null)
                AD_Client_ID = AD_Client.GetKey();

            String startDir = Ini.GetFrameworkHome();
            String fileName = AD_Table.GetValue() + "_" + AD_Language.GetValue() + ".xml";
            if (imp)
            {
                OpenFileDialog chooser = new OpenFileDialog();
                chooser.Filter = "Excel XML Files (*.xml)|*.xml";
                
                if ((bool)chooser.ShowDialog())
                {
                    Import(chooser, AD_Language, AD_Table, AD_Client_ID);
                    #region commentedCode
                    //    ////////////////////////
                    //    //FileInfo info=new FileInfo(chooser.SafeFileName.ToString());

                    //    String directory = "D";//info.FullName; //chooser.SelectedPath;
                    //    /////////////////////
                    //    //


                    //    Translation t = new Translation(Envs.GetCtx());
                    //    String msg = t.ValidateLanguage(AD_Language.GetValue());
                    //    if (msg.Length > 0)
                    //    {
                    //        ShowMessage.Error("LanguageSetupError", true, msg, null);
                    //        return;
                    //    }                

                    //    this.Cursor = Cursors.Wait;
                    //   // SetUI(false);             

                    //    //	All Tables
                    //    if (AD_Table.GetValue().Equals(""))
                    //    {
                    //        for (int i = 1; i < cbTable.Items.Count; i++)
                    //        {
                    //            AD_Table = (ValueNamePair)cbTable.Items[i];//.getItemAt(i);
                    //            msg = null;
                    //            msg = imp
                    //                ? t.ImportTrl(directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue())
                    //                : t.ExportTrl(directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue(),chooser);
                    //            //statusBar.setStatusLine(msg);                    
                    //            //toolStripStatus.Text = msg;
                    //        }
                    //        //statusBar.setStatusLine(directory);
                    //       // toolStripStatus.Text = directory;
                    //    }
                    //    else	//	single table
                    //    {
                    //        msg = null;
                    //        msg = imp
                    //            ? t.ImportTrl(directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue())
                    //            : t.ExportTrl(directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue(),chooser);
                    //        //statusBar.setStatusLine(msg);
                    //        //toolStripStatus.Text = msg;
                    //    }
                    //    //
                    //   // SetUI(true);
                    //    this.Cursor = Cursors.Arrow;
                    //}
                    #endregion
                }
            }
            else
            {
                SaveFileDialog chooser = new SaveFileDialog();
                chooser.Filter = "Excel XML Files (*.xml)|*.xml";
                chooser.DefaultFileName = fileName;
                if ((bool)chooser.ShowDialog())
                {
                   // Stream str = chooser.OpenFile();
                    Export(chooser, AD_Language, AD_Table, AD_Client_ID);
                }
            }
        }


        void Import(OpenFileDialog chooser, ValueNamePair AD_Language, ValueNamePair AD_Table, int AD_Client_ID)
        {
            String directory = chooser.File.DirectoryName;
            Stream stream = chooser.File.OpenRead();
            Translation t = new Translation(Envs.GetCtx());
            ItemCollection items = cbTable.Items;
            lblStatus.SetStatusLine(Msg.GetMsg("Wait"));
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                String msg = t.ValidateLanguage(AD_Language.GetValue());
                if (msg.Length > 0)
                {
                    ShowMessage.Error("LanguageSetupError", true, msg, null);
                    return;
                }
              //  this.Cursor = Cursors.Wait;
                if (AD_Table.GetValue().Equals(""))
                {
                    for (int i = 1; i < items.Count; i++)
                    {
                        AD_Table = (ValueNamePair)items[i];//.getItemAt(i);
                        msg = null;
                        msg = t.ImportTrl(stream, directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue());
                        Dispatcher.BeginInvoke(delegate
                        {
                            lblStatus.SetStatusLine(msg);
                        });
                        //statusBar.setStatusLine(msg);                    
                        //toolStripStatus.Text = msg;
                    }
                    //statusBar.setStatusLine(directory);
                    // toolStripStatus.Text = directory;
                }
                else	//	single table
                {
                    msg = null;
                    msg = t.ImportTrl(stream, directory, AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue());
                    Dispatcher.BeginInvoke(delegate
                    {
                        lblStatus.SetStatusLine(msg);
                    });
                    //statusBar.setStatusLine(msg);
                    //toolStripStatus.Text = msg;
                }
            });
            //
            // SetUI(true);
            this.Cursor = Cursors.Arrow;
        }

        void Export(SaveFileDialog chooser, ValueNamePair AD_Language, ValueNamePair AD_Table, int AD_Client_ID)
        {
           // String directory = "D";
            Translation t = new Translation(Envs.GetCtx());
            ItemCollection items = cbTable.Items;
            lblStatus.SetStatusLine(Msg.GetMsg("Wait"));
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                String msg = t.ValidateLanguage(AD_Language.GetValue());
                Dispatcher.BeginInvoke(delegate
                {
                    if (msg.Length > 0)
                    {
                        ShowMessage.Error("LanguageSetupError", true, msg, null);
                        return;
                    }
                    //this.Cursor = Cursors.Wait;
                    if (AD_Table.GetValue().Equals(""))
                    {
                        for (int i = 1; i < items.Count; i++)
                        {
                            AD_Table = (ValueNamePair)items[i];//.getItemAt(i);
                            msg = null;
                            msg = t.ExportTrl(AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue(), chooser);
                            Dispatcher.BeginInvoke(delegate
                            {
                                lblStatus.SetStatusLine(msg);
                            });
                            //statusBar.setStatusLine(msg);                    
                            //toolStripStatus.Text = msg;
                        }
                        //statusBar.setStatusLine(directory);
                        // toolStripStatus.Text = directory;
                    }
                    else	//	single table
                    {
                        msg = null;
                        msg = t.ExportTrl(AD_Client_ID, AD_Language.GetValue(), AD_Table.GetValue(), chooser);
                        Dispatcher.BeginInvoke(delegate
                        {
                            lblStatus.SetStatusLine(msg);
                        });
                        //statusBar.setStatusLine(msg);
                        //toolStripStatus.Text = msg;
                    }
                });
            });
            //
            // SetUI(true);
            this.Cursor = Cursors.Arrow;
        }


        public void FillClient(DataSet ds)
        {
            //while (dr.Read())
            //{

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                KeyNamePair kp = new KeyNamePair(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
                cbClient.Items.Add(kp);// .addItem(kp);
            }
            //}          
            //dr.Close();
        }
        public void FillLanguage(DataSet ds)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                ValueNamePair vp = new ValueNamePair(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
                cbLanguage.Items.Add(vp);// .addItem(kp);
            }
            cbLanguage.SelectedIndex = 0;

        }
        public void FillTable(DataSet ds)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                ValueNamePair vp = new ValueNamePair(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
                cbTable.Items.Add(vp);// .addItem(kp);
            }
        }
        private void DynInit()
        {
            //	Fill Client
            //IDataReader idr = null;
            //cbClient.addItem(new KeyNamePair(-1, ""));
            cbClient.Items.Add(new KeyNamePair(-1, ""));
            String sqlTenant = "SELECT Name, AD_Client_ID "
                + "FROM AD_Client "
                + "WHERE IsActive='Y' "
                + "ORDER BY 2";

            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset(sqlTenant, null);

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillClient(ds));
                    // idr.Close();
                });



            }
            catch (Exception e)
            {
                //idr.Close();
                log.Log(Level.SEVERE, sqlTenant, e);
            }

            //	Fill Language
            String sqlLanguage = "SELECT Name, AD_Language "
                + "FROM AD_Language "
                + "WHERE IsActive='Y' AND (IsSystemLanguage='Y' OR IsBaseLanguage='Y')"
                + "ORDER BY 1";
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset(sqlLanguage, null);

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillLanguage(ds));

                });


            }
            catch (Exception e)
            {
                // idr.Close();
                log.Log(Level.SEVERE, sqlLanguage, e);
            }
            if (cbLanguage.Items.Count > 0)
            {
                cbLanguage.SelectedIndex = 0;
            }

            //	Fill Table      
            cbTable.Items.Add(new ValueNamePair("", ""));
            String sqlTable = "SELECT Name, TableName "
                + "FROM AD_Table "
                + "WHERE TableName LIKE '%_Trl' AND TableName<>'AD_Column_Trl' "
                + "ORDER BY 1";
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    DataSet ds = new DataSet();
                    ds = DB.ExecuteDataset(sqlTable, null);
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillTable(ds));

                });


            }
            catch (Exception e)
            {
                //idr.Close();
                log.Log(Level.SEVERE, sqlTable, e);
            }
            lblStatus.SetStatusLine("");
            cbTable.SelectedIndex = 0;
            //	Info
            //statusBar.set .setStatusLine(" ");
            //statusBar.setStatusDB(" ");
        }


    }
}
